package com.Mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import java.util.Properties;

@Service
public class MailServer {
    // 类静态的对象，方便只构造一次就可以一直使用
    public static JavaMailSender mailSender;

    // 初始化单例
    @Autowired
    public static void New(){
        JavaMailSender javaMailSender = MailServer.getJavaMailSender();
        mailSender = javaMailSender;
    }

    // 发送邮件
    public static void prepareAndSend(String recipient, String subject, String message){
        MimeMessagePreparator messagePreparator = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);

            // 发送者的邮件
            messageHelper.setFrom("xuexitonglike666@163.com");
            // 接收方的邮件
            messageHelper.setTo(recipient);
            // 主题
            messageHelper.setSubject(subject);
            // 文本
            messageHelper.setText(message);

        };

        try{
            // 发送邮件
            mailSender.send(messagePreparator);
        }catch (MailException e){
            System.out.println("发送失败");
        }
    }


    // 获取sender
    public static JavaMailSender getJavaMailSender(){

        // new一个SenderImpl
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        // 网易邮箱的host
        mailSender.setHost("smtp.163.com");
        // 对应的端口
        mailSender.setPort(25);

        // 发送账号
        mailSender.setUsername("xuexitonglike666@163.com");
        // 授权码
        mailSender.setPassword("YMIILZOABQZCCZLA");

        // 下面几个貌似是mail的属性，不用改
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        // 身份验证
        props.put("mail.smtp.auth", "true");
        // 明文
        props.put("mail.smtp.starttls.enable", "true");
        // debug模式
        props.put("mail.debug", "false");

        return mailSender;
    }
}
